<template>
  <v-card variant="outlined">
    <v-card-title class="d-flex justify-space-between align-center">
      <span>睡眠时长</span> <v-btn
        v-if="canEditToday"
        icon="mdi-pencil"
        variant="text"
        size="small"
        @click="emitEditEvent"
        title="编辑今日总睡眠"
    ></v-btn>
    </v-card-title>

    <v-card-text>
      <div ref="chartRef" style="height: 300px;"></div>
    </v-card-text>
  </v-card>
</template>


<script setup>
import { ref, watch, onMounted, onUnmounted, computed } from 'vue';
import * as echarts from 'echarts';

// --- 1. Props (包含 recommendedRange) ---
const props = defineProps({
  trendData: { type: Array, required: true },
  recommendedRange: { type: Array, default: () => [420, 540] } // [7h, 9h]
});

const chartRef = ref(null);
let chartInstance = null;

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// --- 2. “编辑”按钮逻辑 (来自您原始代码) ---
const emit = defineEmits(['edit']);

const todayData = computed(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const localToday = `${year}-${month}-${day}`;
  return props.trendData.find(d => d.date === localToday);
});

const canEditToday = computed(() => {
  return todayData.value && todayData.value.value > 0;
});

const emitEditEvent = () => {
  if (todayData.value) {
    emit('edit', { date: todayData.value.date, value: todayData.value.value });
  }
};
// --- “编辑”逻辑结束 ---


// --- 3. 【关键修复】动态计算 Y 轴最大值 ---
const yAxisMax = computed(() => {
  const dataMax = Math.max(0, ...props.trendData.map(item => item.value));
  // 逻辑最大值 = 比较 (数据最大值) 和 (推荐睡眠的上限)
  const logicalMax = Math.max(dataMax, props.recommendedRange[1] || 540);

  // 如果数据全是 0，Y 轴最高也显示到推荐的上限 (例如 540 分钟)
  if (logicalMax === 0) {
    return props.recommendedRange[1] || 540;
  }
  // 否则，在最大值上增加 10% 缓冲
  return logicalMax * 1.1;
});
// --- 修复结束 ---


// --- 4. 图表渲染 (合并 visualMap 和 Y 轴修复) ---
const renderChart = () => {
  if (!chartRef.value) return;
  if (chartInstance) {
    chartInstance.dispose();
  }
  chartInstance = echarts.init(chartRef.value);

  const minSleep = props.recommendedRange[0] || 420;
  const maxSleep = props.recommendedRange[1] || 540;

  chartInstance.setOption({
    // (A) 视觉映射 (来自您的代码)
    visualMap: {
      type: 'piecewise',
      show: false,
      dimension: 1,
      pieces: [
        {lt: minSleep, color: '#FFA500'}, // 不足
        {gte: minSleep, lte: maxSleep, color: '#32CD32'}, // 达标
        {gt: maxSleep, color: '#87CEFA'}  // 过量
      ]
    },

    // (B) Tooltip 格式化 (来自您的代码)
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const data = params[0];
        const value = data.value;
        const hours = Math.floor(value / 60);
        const minutes = value % 60;
        return `${data.name}<br/>${data.seriesName}: ${hours} 小时 ${minutes} 分钟`;
      }
    },

    xAxis: {type: 'category', data: props.trendData.map(item => item.date)},

    // (C) Y 轴 (合并格式化 和 max 修复)
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => {
          const hours = Math.floor(value / 60);
          return `${hours} h`; // Y轴显示小时
        }
      },
      // 应用 Y 轴最大值修复
      max: yAxisMax.value
    },

    series: [{
      name: '睡眠时长', type: 'bar',
      data: props.trendData.map(item => item.value),
    }],
    grid: {left: '3%', right: '4%', bottom: '3%', containLabel: true}
  });
};

// --- 5. 监听和生命周期 ---
watch(() => [props.trendData, props.recommendedRange], renderChart, {deep: true, immediate: true});

onMounted(() => {
  renderChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>